package collector.parsers;

import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import collector.support.URLHandler;

public class StockMarketListFinder extends Thread implements Iterable<String> {
	private URLHandler urlHandler;
	private HashMap<String, String> matches;
	private String market;
	private Semaphore parsing;

	public StockMarketListFinder(String market) {
		parsing = new Semaphore(1);
		try {
			parsing.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.market = market;
		this.start();
	}

	public void run() {
		urlHandler = URLHandler
				.create("https://www.avanza.se/aza/aktieroptioner/kurslistor/kurslistor.jsp?cc="
						+ market);
		matches = new HashMap<String, String>();
		String content = urlHandler.getContent();
		Pattern selectPattern = Pattern
				.compile(
						"<select name=\"lkey\".*?>(.*?<option.*?value=\"([^\"]*)\".*?>([^<]*)</option>.*?)?</select>",
						Pattern.CASE_INSENSITIVE);
		Matcher selectMatcher = selectPattern.matcher(content);
		String optionsString = null;
		try {
			while (selectMatcher.find()) {
				optionsString = selectMatcher.group(1).trim();
				// System.out.println(optionsString);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		Pattern optionPattern = Pattern.compile(
				"<option.*?value=\"([^\"]*)\".*?>([^<]*)</option>",
				Pattern.CASE_INSENSITIVE);
		Matcher optionMatcher = optionPattern.matcher(optionsString);
		while (optionMatcher.find()) {
			String code = optionMatcher.group(1).trim();
			String name = optionMatcher.group(2).trim();
			// System.out.println(name + " = " + code);
			matches.put(code, name);
		}
		
		//TODO: sublist finder, NYSE has alphabetical sublists...

		parsing.release();
	}

	public HashMap<String, String> getLists() {
		try {
			parsing.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		HashMap<String, String> result = matches;
		parsing.release();
		return result;
	}

	@Override
	public Iterator<String> iterator() {
		return getLists().keySet().iterator();
	}
}
